/**
 * Created by GUO on 2017/5/19.
 * @flow
 * 站点
 */

import React from 'react';
import {
    View,
    Text,
    StyleSheet,
    Image,
    Platform,
    ActivityIndicator,
    SectionList,
} from 'react-native';
import BaseScreen from '../BaseScreen';
import Icon from 'react-native-vector-icons/MaterialIcons';
import HttpClient from '../HttpClient';
import RssItem from '../rss/RssItem';
import RssSection from '../rss/RssSection';

const makeTitleBarButtons = (onPress:? (key: string)=>void)=> {
    let searchButton = (<Icon
        onPress={()=> onPress && onPress('search')}
        name="search"
        size={24}
        color="white"
        style={styles.titleBarIcon}/>);

    let moreButton = (<Icon
        onPress={()=> onPress && onPress('more')}
        name={Platform.select({ios:'more-horiz',android:'more-vert'})}
        size={24}
        color="white"
        style={styles.titleBarIcon}/>);

    return Platform.select({
        ios:{headerLeft:searchButton,headerRight:moreButton},
        android:{
            headerRight:<View style={styles.barButtonContainer}>{searchButton}{moreButton}</View>
        }
    });

};

export default class TopicScreen extends BaseScreen {

    static navigationOptions = ({navigation}) => {
        let {onPressTitleBarButton} = navigation.state.params || {};

        return {
            title: '主题',
            tabBarIcon: ({ tintColor }) => (
                <Icon size={26} color={tintColor} name="local-offer"/>
            ),
            ...makeTitleBarButtons(onPressTitleBarButton)
        };
    };

    state = {
        items:[], //原始数据
        sections:[],
        fetching: true,
        refreshing: false,
    };

    _fetchData(){
        HttpClient.get('/topics/my_with_dirs.json').then(response => {

            let { items } = response.data;

            this.setState({
                fetching:false,
                refreshing:false,
                items,
                sections:this._makeSections(items,['0'])
            });

        }).catch(e => {
            this.setState({
                fetching:false
            });
            console.log('=err====>>',e);
        });
    }

    _makeSections(items: Array<Object>,expandedIds:Array<string> = []): Array<Object>{
        return items.map(item => {

            let section = {
                key:String(item.id),
                id:item.id,
                name:item.name,
                expanded:false,
                data:[]
            };

            if(expandedIds.findIndex(id => id == item.id) != -1){
                section.data = [...item.items];
                section.expanded = true;
            }
            return section;
        });
    }

    componentDidMount(){
        this._fetchData();
    }

    render(){
        if(this.state.fetching){
            return <ActivityIndicator/>
        }else if(this.state.sections.length>0){
            return <SectionList
                initialNumToRender = {12}
                keyExtractor = {(item,index) => item.id}
                onRefresh={()=> this.setState({refreshing:true},()=>this._fetchData(true))}
                refreshing={this.state.refreshing}
                stickySectionHeadersEnabled = {false}
                style={{flex:1}}
                sections = {this.state.sections}
                renderSectionHeader={this._renderSection.bind(this)}
                renderItem = {this._renderItem.bind(this)}
            />
        }else{
            return <Text>数据为空／超时</Text>
        }
    }

    _renderSection({section}){
        return <RssSection
            onPress={()=>this._onPressSection(section)}
            data={section}
        />
    }

    _onPressSection(section){
        let expandedIds: Array<string> = [];
        this.state.sections.forEach(item => {
            if((item.id === section.id && !item.expanded) || (item.id != section.id && item.expanded)){
                expandedIds.push(String(item.id));
            }
        });

        this.setState({sections:this._makeSections(this.state.items,expandedIds)})
    }

    _renderItem({item}){
        return <RssItem data={item}/>
    }
}

const styles = StyleSheet.create({
    container:{
        flex:1,
    },
    barButtonContainer:{
        flexDirection:'row'
    },
    titleBarIcon:{
        paddingHorizontal:10,
    },
});